<template>
  <section>
    <u-form :schema="formSchema" :dataSource="loginForm" ref="form">
      <template #footer>
        <u-button @click="handleOnClickToLogin" type="primary" color="#F00"
          >登录</u-button
        >
        <u-button @click="$router.push('/reg')" type="primary" color="#F00"
          >注册</u-button
        >
      </template>
    </u-form>
  </section>
</template>

<script>
import { mapMutations } from "vuex";

import { login } from "../../access/api/user/index";

import UICLI from "components/ui-cli";

import { FormItemType } from "assets/js/Constant";

import { handleOnValidate2LoginName } from "assets/js/Validate";

const formSchema = {
  options: {
    labelCol: 4,
    wrapperCol: 20,
    layout: "vertical",
  },
  groups: [
    {
      grid: 1,
      fields: [
        {
          type: FormItemType.INPUT, // password textarea number
          label: "登录账号",
          name: "loginName",
          placeholder: "邮箱/手机号",
          rules: [
            { required: true, message: "请输入登录账号" },
            { validator: handleOnValidate2LoginName },
          ],
        },
        {
          type: FormItemType.PASSWORD,
          label: "登录密码",
          name: "loginPwd",
          placeholder: "密码",
          rules: [{ required: true, message: "请输入登录密码" }],
        },
      ],
    },
  ],
};

import { hex_md5, showMess } from "utils/Util";

export default {
  name: "Login",
  components: {
    UForm: UICLI.UForm,
    UButton: UICLI.UButton,
  },
  data() {
    return {
      FormItemType,
      formSchema,
      loginForm: {
        loginName: "",
        loginPwd: "",
      },
    };
  },
  methods: {
    ...mapMutations(["updateToken", "updateLoginUrl", "clear"]),
    handleOnClickToLogin() {
      this.$refs.form.$refs.form
        .validate()
        .then(() => {
          const loginPwd = hex_md5(this.loginForm.loginPwd);

          login({
            loginName: this.loginForm.loginName,
            loginPwd: loginPwd,
          }).then((res) => {
            if (res) {
              // 登录成功
              showMess("登录成功");
              this.updateToken(res);
              this.updateLoginUrl(this.$route.path);

              this.$router.push("/app");
            }
          });
        })
        .catch((error) => {
          console.log("error", error);
        });
    },
  },
  created() {
    this.clear();
  }
};
</script>

<style lang="less" scoped>
</style>